package net.dgg.rz.common.utils;

import com.alibaba.fastjson.JSONObject;
import net.dgg.rz.production.entity.dto.UserLevelDto;

import java.lang.reflect.Method;
import java.util.List;

/**
 * 对象工具类
 * @author changbo
 *
 */
public class ObjectUtil {

	/**
	 * 获取对象的属性
	 * @param obj
	 * @param field
	 * @return
	 */
	public static Object getFieldValue(Object obj, String field){
		if(field == null){
			return null;
		}
		String f = field.substring(0, 1);
		String methodName = "get" + f.toUpperCase() + field.substring(1);
		try {
			Method method = obj.getClass().getMethod(methodName);
			method.setAccessible(true);
			return method.invoke(obj);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 获取对象的属性（有json对象的数据）
	 * @param obj
	 * @param field
	 * @return
	 */
	public static Object getFieldJson(Object obj, String field){
		if(field == null){
			return null;
		}
		try {
			String f = field.substring(0, 1);
			String methodName = "";
			if(field.indexOf(".")>0){
				String jStr = field.substring(field.indexOf(".")+1,field.length());
				methodName = "get" + f.toUpperCase() + field.substring(1,field.indexOf("."));
				Method method = obj.getClass().getMethod(methodName);
				method.setAccessible(true);
				Object object = method.invoke(obj);
				if(object != null && object instanceof JSONObject){
					JSONObject jsonObject = (JSONObject) object;
					return jsonObject.get(jStr);
				}else {
					return null;
				}
			}else {
				methodName = "get" + f.toUpperCase() + field.substring(1);
				Method method = obj.getClass().getMethod(methodName);
				method.setAccessible(true);
				return method.invoke(obj);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}


	public static void main(String[] args){
		UserLevelDto userLevelDto = new UserLevelDto();
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("test1",3250.00);
		jsonObject.put("test2",1250.60);
		userLevelDto.setUserId(3242L);
		userLevelDto.setRetJson(jsonObject);
		Object object = getFieldJson(userLevelDto,"retJson.test1");
		if(object instanceof JSONObject){}
	}

}
